export function wxLogin(vm) {
	return new Promise((resolve, reject) => {
		if (vm.vuex_token) {
			return reject();
		}
		let _this = vm;
		uni.showModal({
			title: '温馨提示',
			content: '亲，授权微信登录后才能正常使用小程序功能',
			success(res) {
				//如果用户点击了确定按钮
				if (res.confirm) {
					getUserProfile(vm).then((res)=>{
						resolve(res);
					}).catch(err => {
						reject(err);
					});
				} else if (res.cancel) {
					//如果用户点击了取消按钮
					uni.showToast({
						title: '您拒绝了授权',
						icon: 'error',
						duration: 2000
					});
					reject();
				}
			}
		});
	});
}


export function getUserProfile(vm) {
	return new Promise((resolve, reject) => {
	   let _this = vm;
	   uni.getUserProfile({
	   	desc: '获取你的昵称、头像、地区及性别',
	   	success: res => {
	   		_this.$u.vuex("vuex_user", res.userInfo);
	   		getWechatOpenId(res.userInfo,vm).then((res)=>{
				resolve(res);
			},(error)=>{
				reject(res);
			})
	   	},
	   	fail: res => {
	   		console.log(res)
	   		//拒绝授权
	   		uni.showToast({
	   			title: '您拒绝了授权',
	   			icon: 'error',
	   			duration: 2000
	   		});
	   		reject(res);
	   	}
	   });
	});
}	


export function getWechatOpenId(userInfo,vm) {
	let _this = vm;
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			success: function(loginRes) {
				//从服务器上获取AppId screat //根据code 去微信服务器获取 openid
				_this.$u.api.getWechatOpenId({
					code: loginRes.code
				}).then(res => {
					if (!res.data) {
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							duration: 2000,
							position: 'bottom',
							title: '登录失败'
						});
						reject(res);
					}
					let authUser = {
						openId: res.data,
						nickName: userInfo.nickName,
						avatar: userInfo.avatarUrl
					};
					_this.$u.vuex("vuex_user.openId", res.data);
					_this.$u.api.wechatLogin(authUser).then(res => {
						uni.showToast({
							icon: 'none',
							duration: 2000,
							position: 'bottom',
							title: '登录成功'
						});
						let token = res.data.token;
						let gameUser = res.data.gameUser;
						let gameId = res.data.gameId;
						console.log("gameUser",gameUser);
						_this.$u.vuex("vuex_token", token);
						_this.$u.vuex("vuex_user.gameUser", gameUser);
						_this.$u.vuex("vuex_user.gameId", gameId);
						resolve(_this.vuex_user);
					});
				});
			},
			fail: function(res) {
				uni.showToast({
					icon: 'none',
					duration: 2000,
					position: 'bottom',
					title: '登录失败'
				});
				reject(res);
			}
		});
	});
}